package com.quectel.cms.controller.sys;


import com.google.common.base.Preconditions;
import com.quectel.cms.constants.CmsRedisCacheConstants;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.interceptor.LoginUserSession;
import com.quectel.cms.util.RegionUtils;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.sys.*;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysConstants;
import com.quectel.constant.sys.SysGroupConstants;
import com.quectel.core.module.device.dto.DeviceCategoryDto;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.dto.DeviceTypeDto;
import com.quectel.core.module.device.service.DeviceCategoryService;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.device.service.DeviceTypeService;
import com.quectel.core.module.group.dto.*;
import com.quectel.core.module.group.service.*;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.sys.module.sys.dto.SysGroupDto;
import com.quectel.sys.module.sys.dto.SysUserDto;
import com.quectel.sys.module.sys.service.SysGroupService;
import com.quectel.util.common.*;
import com.quectel.util.ex.CheckErrorException;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.redis.RedisUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2019-05-31 11:40:38
 */
@RestController
@RequestMapping("sysGroup")
@Tag(name = "SysGroupController", description = "系统组相关api")
public class SysGroupController extends BaseController {

    @DubboReference
    private SysGroupService sysGroupService;
    @DubboReference
    private DeviceCategoryService deviceCategoryService;
    @DubboReference
    private DeviceTypeService deviceTypeService;
    @DubboReference
    private SysGroupDeviceCategoryService sysGroupDeviceCategoryService;
    @DubboReference
    private SysGroupDeviceTypeService sysGroupDeviceTypeService;
    @DubboReference
    private SysGroupDeviceService sysGroupDeviceService;
    @DubboReference
    private DeviceService deviceService;
    @DubboReference
    private SysGroupVillageService sysGroupVillageService;
    @DubboReference
    private SysGroupRegionService sysGroupRegionService;
    @DubboReference
    private SysRegionVillageRefService sysRegionVillageRefService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private VillageBuildingService villageBuildingService;
    @DubboReference
    private SysGroupBuildingService sysGroupBuildingService;
    @DubboReference
    private PartyOrganizationService partyOrganizationService;

    // 区域组权限操作lock key (区域分级调整)
    private static final String REGION_GROUP_OPERATE_LOCK = CmsRedisCacheConstants.PROJECT_NAME
            + "REGION_GROUP_OPERATE_LOCK:";


    @GetMapping("tree")
    @Operation(summary = "系统组树结构数据查询")
    public Response<List<SysGroupTreeDataVo>> tree() {
        List<SysGroupTreeDataVo> result = new ArrayList<>();

        Long groupId = SessionHolder.getSysUser().getGroupId();
        if (groupId == null || groupId < 0) {
            return Response.<List<SysGroupTreeDataVo>>ok().wrap(result);
        }

        List<SysGroupDto> sysGroupDtoList = sysGroupService.selectByParentId(groupId);
        sysGroupDtoList.add(sysGroupService.selectById(groupId));

        result = treeBuilder(sysGroupDtoList, groupId);
        return Response.<List<SysGroupTreeDataVo>>ok().wrap(result);
    }

    private List<SysGroupTreeDataVo> treeBuilder(List<SysGroupDto> groupDtoList, Long rootId) {
        List<SysGroupTreeDataVo> groups = new ArrayList<>();

        List<SysGroupTreeDataVo> sysGroupTreeDataVos = CopyUtils.copyList(groupDtoList, SysGroupTreeDataVo.class);
        for (SysGroupTreeDataVo c1 : sysGroupTreeDataVos) {
            if (Objects.equals(rootId, c1.getId())) {
                groups.add(c1);
            }
            for (SysGroupTreeDataVo c2 : sysGroupTreeDataVos) {
                if (c2.getParentId().equals(c1.getId())) {
                    if (c1.getChildes() == null) {
                        c1.setChildes(new ArrayList<>());
                    }
                    c2.setParentName(c1.getName());
                    c1.getChildes().add(c2);
                }
            }
        }
        return groups;
    }

    /**
     * 系统组用户列表查询
     */
    @GetMapping("subUserQuery")
    @Operation(summary = "系统组用户列表查询")
    public Response<List<SysUserDto>> subUserQuery() {

        Long groupId = SessionHolder.getSysUser().getGroupId();

        List<SysUserDto> list = sysGroupService.getSubUsers(groupId);

        return Response.<List<SysUserDto>>ok().wrap(list);
    }


    @GetMapping("groupAuthPush")
    @RequirePermissions(values = "sysGroup:authPush")
    @Operation(summary = "系统组数据授权移入")
    public Response<Object> groupAuthPush(Long parentGroupId, Long groupId, @RequestParam("objIds[]") Long[] objIds) {
        SysGroupDto sysGroupDto = sysGroupService.selectById(groupId);
        SysGroupDto sysParentGroupDto = sysGroupService.selectById(parentGroupId);

        if (Objects.isNull(sysGroupDto) || Objects.isNull(sysParentGroupDto)) {
            return Response.error("缺少组id");
        }

        /*
         *  <p>
                                            '类型'权限类型组织下只能建立'设备'、'类型'权限类型组织
                                        </p>
                                        <p>
                                            '设备'权限类型组织下只能建立'设备'权限类型组织
                                        </p>
                                        <p>
                                            '社区'权限类型组织下只能建立'社区'、'楼栋'、'设备'权限类型组织
                                        </p>
                                        <p>
                                            '区域'权限类型组织下只能建立'区域'、'社区'、'楼栋'、'设备'权限类型组织
                                        </p>
                                        <p>
                                            '楼栋'权限类型组织下只能建立'楼栋'、'设备'权限类型组织
                                        </p>
                                        </br>
                                        <p>
                                            最顶级组不受该约束
                                        </p>
         */

        if (!SysConstants.SYS_TOP_GROUP_CODE.equals(sysParentGroupDto.getCode())) {
            if (
                    SysConstants.GroupAuthEnum.BY_REGION.getType().equals(sysParentGroupDto.getAuthorityType())
                            && SysConstants.GroupAuthEnum.BY_TYPE.getType().equals(sysGroupDto.getAuthorityType())
                            ||


                            SysConstants.GroupAuthEnum.BY_VILLAGE.getType().equals(sysParentGroupDto.getAuthorityType())
                                    && SysConstants.GroupAuthEnum.BY_TYPE.getType().equals(sysGroupDto.getAuthorityType())
                            ||
                            SysConstants.GroupAuthEnum.BY_VILLAGE.getType().equals(sysParentGroupDto.getAuthorityType())
                                    && SysConstants.GroupAuthEnum.BY_REGION.getType().equals(sysGroupDto.getAuthorityType())
                            ||


                            SysConstants.GroupAuthEnum.BY_TYPE.getType().equals(sysParentGroupDto.getAuthorityType())
                                    && SysConstants.GroupAuthEnum.BY_REGION.getType().equals(sysGroupDto.getAuthorityType())
                            ||
                            SysConstants.GroupAuthEnum.BY_TYPE.getType().equals(sysParentGroupDto.getAuthorityType())
                                    && SysConstants.GroupAuthEnum.BY_VILLAGE.getType().equals(sysGroupDto.getAuthorityType())
                            ||
                            SysConstants.GroupAuthEnum.BY_TYPE.getType().equals(sysParentGroupDto.getAuthorityType())
                                    && SysConstants.GroupAuthEnum.BY_BUILDING.getType().equals(sysGroupDto.getAuthorityType())
                            ||


                            SysConstants.GroupAuthEnum.BY_DEVICE.getType().equals(sysParentGroupDto.getAuthorityType())
                                    && !SysConstants.GroupAuthEnum.BY_DEVICE.getType().equals(sysGroupDto.getAuthorityType())
            ) {
                return Response.error("非法的上下级权限关系");
            }
        }

        boolean fatherIsSuper = false;
        if ("Super_Group".equals(sysParentGroupDto.getCode())) {
            fatherIsSuper = true;
        }

        Byte authorityType = sysGroupDto.getAuthorityType();
        List<DeviceDto> parentGroupMangeDeviceList = new ArrayList<>();
        List<Long> parentGroupMangeVillageIds = new ArrayList<>();
        if (!fatherIsSuper) {
            // 导入的是小区权限 不需要知道父组的设备
            if (authorityType != 3) {
                //查询父级组数据权限
                HashMap<String, Object> params = new HashMap<>();
                super.fillTenantData(params);
                params.put("_sysGroup", sysParentGroupDto);
                params.put("limit", 1000);
                int pageNo = 1;
                while (true) {
                    params.put("offset", (pageNo - 1) * 1000);
                    List<DeviceDto> deviceDtoList = deviceService.queryList(params);
                    if (deviceDtoList.size() <= 0) {
                        break;
                    }
                    parentGroupMangeDeviceList.addAll(deviceDtoList);
                    pageNo++;
                }
            }
            if (new Byte((byte) 3).equals(sysParentGroupDto.getAuthorityType())) {
                parentGroupMangeVillageIds = sysGroupVillageService.queryListByGroupId(parentGroupId).stream().map(o -> o.getVillageId()).collect(Collectors.toList());
            } else if (new Byte((byte) 4).equals(sysParentGroupDto.getAuthorityType())) {
                parentGroupMangeVillageIds = sysGroupRegionService.queryVillageIds(parentGroupId);
            }

        }

        int count = 0;
        switch (authorityType) {
            case 2: {
                // 设备权限组
                SysGroupDeviceDto sysGroupDeviceDto = new SysGroupDeviceDto();
                sysGroupDeviceDto.setSysGroupId(groupId);
                if (fatherIsSuper) {
                    for (Long objId : objIds) {
                        sysGroupDeviceDto.setDeviceId(objId);
                        sysGroupDeviceService.deleteByGroupIdAndDeviceId(groupId, objId);
                        sysGroupDeviceService.save(sysGroupDeviceDto);
                        count++;
                    }
                } else {
                    for (Long objId : objIds) {
                        for (DeviceDto deviceDto : parentGroupMangeDeviceList) {
                            if (objId.equals(deviceDto.getId())) {
                                sysGroupDeviceDto.setDeviceId(objId);
                                sysGroupDeviceService.deleteByGroupIdAndDeviceId(groupId, objId);
                                sysGroupDeviceService.save(sysGroupDeviceDto);
                                count++;
                                break;
                            }
                        }
                    }
                }
                return Response.ok().wrap("已经成功导入" + count + "条数据,若少于勾选条数可查看父组是否拥有该权限");
            }
            case 3: {
                // 小区权限组
                SysGroupVillageDto sysGroupVillageDto = new SysGroupVillageDto();
                sysGroupVillageDto.setSysGroupId(groupId);
                if (fatherIsSuper) {
                    for (Long objId : objIds) {
                        sysGroupVillageDto.setVillageId(objId);
                        sysGroupVillageService.deleteByGroupIdAndVillageId(groupId, objId);
                        sysGroupVillageService.save(sysGroupVillageDto);
                        count++;
                    }
                } else {
                    for (Long objId : objIds) {
                        for (Long parentVillageId : parentGroupMangeVillageIds) {
                            if (objId.equals(parentVillageId)) {
                                sysGroupVillageDto.setVillageId(objId);
                                sysGroupVillageService.deleteByGroupIdAndVillageId(groupId, objId);
                                sysGroupVillageService.save(sysGroupVillageDto);
                                count++;
                                break;
                            }
                        }
                    }
                }
                return Response.ok().wrap("已经成功导入" + count + "条数据,若少于勾选条数可查看父组是否拥有该权限");
            }
        }
        return Response.error("组权限类型未知");
    }

    @GetMapping("groupAuthPop")
    @RequirePermissions(values = "sysGroup:authPop")
    @Operation(summary = "系统组数据授权移出")
    public Response<Object> groupAuthPop(Long groupId, @RequestParam("objIds[]") Long[] objIds) {
        SysGroupDto sysGroupDto = sysGroupService.selectById(groupId);
        if (Objects.isNull(sysGroupDto)) {
            return Response.error("缺少组id");
        }

        List<SysGroupDto> childGroups = sysGroupService.selectByParentId(groupId);

        Byte authorityType = sysGroupDto.getAuthorityType();
        switch (authorityType) {
            case 2: {
                // 设备权限组
                for (Long objId : objIds) {
                    sysGroupDeviceService.deleteByGroupIdAndDeviceId(groupId, objId);
                    for (SysGroupDto childGroup : childGroups) {
                        sysGroupDeviceService.deleteByGroupIdAndDeviceId(childGroup.getId(), objId);
                    }
                }
                return Response.ok();
            }
            case 3: {
                // 小区权限组
                // 如果子用户组为设备权限情况
                List<DeviceDto> lists = null;
                for (Long objId : objIds) {
                    lists = new ArrayList<>();
                    sysGroupVillageService.deleteByGroupIdAndVillageId(groupId, objId);
                    for (SysGroupDto childGroup : childGroups) {
                        if (childGroup.getAuthorityType() == 2) {
                            if (lists.isEmpty()) {
                                lists = deviceService.queryList(new HashMap<String, Object>() {{
                                    put("villageId", objId);
                                }});
                            }
                            for (DeviceDto dto : lists) {
                                sysGroupDeviceService.deleteByGroupIdAndDeviceId(childGroup.getId(), dto.getId());
                            }
                        } else {
                            sysGroupVillageService.deleteByGroupIdAndVillageId(childGroup.getId(), objId);
                        }
                    }
                }
                return Response.ok();
            }
            case 4: {
                // 区域权限组
                for (Long objId : objIds) {
                    SysGroupRegionDto sysGroupRegionDto = sysGroupRegionService.selectById(objId);
                    if (sysGroupRegionDto == null) {
                        continue;
                    }
                    sysGroupRegionService.deleteById(sysGroupRegionDto.getId());
                    for (SysGroupDto childGroup : childGroups) {
                        sysGroupRegionService.deleteByGroupIdAndLikeCode(childGroup.getId(), sysGroupRegionDto.getCode());
                    }
                }
                return Response.ok();
            }
        }
        return Response.error("组权限类型未知");
    }

    @GetMapping("queryAuthBuildingData")
    @RequirePermissions(values = "sysGroup:buildingList")
    @Operation(summary = "查询可授权的楼栋数据")
    public Response<AuthBuildingResp> queryAuthBuildingData(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Request request = Request.configParams(params);

        SysGroupDto sysGroupDto = sysGroupService.selectById(request.getLong("groupId"));
        if (sysGroupDto == null) {
            throw new CheckErrorException("用户组ID必须分配");
        }
        super.fillTenantData(params);
        SysGroupDto parentGroup = sysGroupService.selectById(sysGroupDto.getParentId());
        params.put("_sysGroup", parentGroup);

        AuthBuildingResp authBuildingResp = new AuthBuildingResp();
        authBuildingResp.setCanSelectData(villageBuildingService.queryList(params));

        params.put("_sysGroup", sysGroupDto);
        authBuildingResp.setSelectIds(villageBuildingService.queryList(params).stream().map(VillageBuildingDto::getId).collect(Collectors.toList()));


        return Response.<AuthBuildingResp>ok().wrap(authBuildingResp);
    }

    /**
     * 保存系统组的楼栋权限数据
     */
    @PostMapping("saveBuildingAuthority")
    @RequirePermissions(values = "sysGroup:authorize")
    @Operation(summary = "保存系统组的楼栋权限数据")
    public Response<Object> saveBuildingAuthority(@RequestBody AuthBuildingReq authBuildingReq) {

        if (authBuildingReq.getBuildingIds() != null && authBuildingReq.getBuildingIds().size() > 0) {

            Map<String, Object> params = new HashMap<>();
            super.fillTenantData(params);
            SysGroupDto parentGroup = sysGroupService.selectById(authBuildingReq.getParentGroupId());
            params.put("_sysGroup", parentGroup);
            List<Long> parentIds = villageBuildingService.queryList(params).stream().map(VillageBuildingDto::getId).collect(Collectors.toList());
            for (Long buildingId : authBuildingReq.getBuildingIds()) {

                if (!parentIds.contains(buildingId)) {
                    //非法的数据操作
                    return Response.error(SystemConstants.ILLEGAL_MSG);
                }
            }
            sysGroupBuildingService.deleteByGroupId(authBuildingReq.getGroupId());
            for (Long buildingId : authBuildingReq.getBuildingIds()) {
                SysGroupBuildingDto sysGroupBuildingDto = new SysGroupBuildingDto();
                sysGroupBuildingDto.setSysGroupId(authBuildingReq.getGroupId());
                sysGroupBuildingDto.setBuildingId(buildingId);
                sysGroupBuildingService.save(sysGroupBuildingDto);
            }
        }

        return Response.ok();
    }


    /**
     * 查询系统组可授权的小区列表
     *
     * @param params
     * @return
     */
    @GetMapping("canSelectVillageList")
    @RequirePermissions(values = "sysGroup:villageList")
    @Operation(summary = "查询系统组可授权的小区列表")
    public Response<Page<VillageDto>> canSelectVillageList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Request request = Request.configParams(params);

        SysGroupDto sysGroupDto = sysGroupService.selectById(request.getLong("groupId"));
        if (sysGroupDto == null) {
            throw new CheckErrorException("用户组ID必须分配");
        }
        super.fillTenantData(params);
        SysGroupDto parentGroup = sysGroupService.selectById(sysGroupDto.getParentId());
        params.put("_sysGroup", parentGroup);

        params.put("unAuthedVillage", String.valueOf(SystemConstants.YES));
        params.put("unAuthedGroupId", sysGroupDto.getId());

        List<VillageDto> list = new ArrayList<>();

        int total = villageService.queryTotal(params);
        if (total > 0) {
            list = villageService.queryList(params);
        }

        Page<VillageDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<VillageDto>>ok().wrap(page);
    }

    /**
     * 查询系统组授权的小区列表
     *
     * @param params
     * @return
     */
    @GetMapping("villageList")
    @RequirePermissions(values = "sysGroup:villageList")
    @Operation(summary = "查询系统组授权的小区列表")
    public Response<Page<VillageDto>> villageList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Request request = Request.configParams(params);

        SysGroupDto sysGroupDto = sysGroupService.selectById(request.getLong("groupId"));
        if (sysGroupDto == null) {
            throw new CheckErrorException("用户组ID必须分配");
        }
        super.fillTenantData(params);
        params.put("_sysGroup", sysGroupDto);

        List<VillageDto> list = villageService.queryList(params);
        int total = villageService.queryTotal(params);

        Page<VillageDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<VillageDto>>ok().wrap(page);
    }


    @GetMapping("getRegionInfo")
    @Operation(summary = "根据条件查询地区信息列表")
    public Response<Page<RegionUtils.ReignStruct>> getRegionInfo(@RequestParam Map<String, Object> params) {
        List<RegionUtils.ReignStruct> list = new ArrayList<>();

        int total = 0;
        Request request = Request.configParams(params);

        if (params.containsKey("level")) {

            Byte level = Byte.valueOf(params.get("level") + "");
            String name = params.get("name") + "";
            list = RegionUtils.getByLevelAndName(level, name);
            total = list.size();

            list.sort(Comparator.comparing(RegionUtils.ReignStruct::getCode));
            if (total >= (request.getPageNo() - 1) * request.getPageSize() + request.getPageSize()) {
                list = list.subList((int) params.get("offset"), (int) params.get("offset") + request.getPageSize());
            } else if (total >= (int) params.get("offset")) {
                list = list.subList((int) params.get("offset"), list.size());
            } else {
                list = new ArrayList<>();
            }
        }

        Page<RegionUtils.ReignStruct> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<RegionUtils.ReignStruct>>ok().wrap(page);

    }

    private boolean havaAuthority(String code, List<SysGroupRegionDto> list) {
        for (SysGroupRegionDto sysGroupRegionDto : list) {
            if (Objects.equals(code, sysGroupRegionDto.getCode())) {
                return true;
            }
        }
        RegionUtils.ReignStruct byCode = RegionUtils.getByCode(code);
        String parentCode = byCode.getParentCode();
        if (StringUtils.isBlank(parentCode)) {
            return false;
        }
        return havaAuthority(parentCode, list);
    }

    @GetMapping("regionList")
    @RequirePermissions(values = "sysGroup:regionList")
    @Operation(summary = "根据条件查询系统组地区列表")
    public Response<Page<SysGroupRegionVo>> regionList(@RequestParam Map<String, Object> params) {
        Request request = Request.configParams(params);

        SysGroupDto sysGroupDto = sysGroupService.selectById(request.getLong("sysGroupId"));
        if (sysGroupDto == null) {
            return Response.error("null group");
        }

        int total = sysGroupRegionService.queryTotal(params);
        List<SysGroupRegionDto> sysGroupRegionDtos = new ArrayList<>();

        if (total > 0) {
            sysGroupRegionDtos = sysGroupRegionService.queryList(params);
        }

        List<SysGroupRegionVo> result = sysGroupRegionDtos.stream().map(o -> {
            SysGroupRegionVo sysGroupRegionVo = new SysGroupRegionVo();
            sysGroupRegionVo.setId(o.getId());

            RegionUtils.ReignStruct regionCache = getRegionCache(o.getCode());
            if (regionCache == null) {
                return null;
            }

            sysGroupRegionVo.setLevel(regionCache.getLevel());

            Byte level = regionCache.getLevel();

            do {
                switch (level) {
                    case 1:
                        sysGroupRegionVo.setProvinceCode(regionCache.getCode());
                        sysGroupRegionVo.setProvinceName(regionCache.getName());
                        break;
                    case 2:
                        sysGroupRegionVo.setCityCode(regionCache.getCode());
                        sysGroupRegionVo.setCityName(regionCache.getName());
                        break;
                    case 3:
                        sysGroupRegionVo.setDistrictCode(regionCache.getCode());
                        sysGroupRegionVo.setDistrictName(regionCache.getName());
                        break;
                    case 4:
                        sysGroupRegionVo.setStreetCode(regionCache.getCode());
                        sysGroupRegionVo.setStreetName(regionCache.getName());
                        break;
                }

                regionCache = getRegionCache(regionCache.getParentCode());
                if (regionCache == null) {
                    level = -1;
                } else {
                    level = regionCache.getLevel();
                }

            } while (level >= 1);

            return sysGroupRegionVo;
        }).filter(o -> o != null).collect(Collectors.toList());

        Page<SysGroupRegionVo> page = new Page<>(request.getPageNo(), request.getPageSize(), total, result);
        return Response.<Page<SysGroupRegionVo>>ok().wrap(page);
    }

    private RegionUtils.ReignStruct getRegionCache(String code) {
        RegionUtils.ReignStruct struct = CacheKit.cacheToRedis(
                () -> RegionUtils.getByCode(code),
                "SYS_GROUP_REGION_CODE_NAME_BIND_" + code,

                15 * 60
        );
        return struct;
    }

    /**
     * 查询可授权的设备列表
     */
    @GetMapping("canSelectDeviceList")
    @RequirePermissions(values = "sysGroup:deviceList")
    @Operation(summary = "查询可授权的设备列表")
    public Response<Page<DeviceDto>> canSelectDeviceList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Request request = Request.configParams(params);

        SysGroupDto sysGroupDto = sysGroupService.selectById(request.getLong("groupId"));
        if (sysGroupDto == null) {
            throw new CheckErrorException("用户组ID必须分配");
        }
        super.fillTenantData(params);
        SysGroupDto parentGroup = sysGroupService.selectById(sysGroupDto.getParentId());
        params.put("_sysGroup", parentGroup);

        params.put("unAuthedDevice", String.valueOf(SystemConstants.YES));
        params.put("unAuthedGroupId", sysGroupDto.getId());

        List<DeviceDto> list = deviceService.queryList(params);
        int total = deviceService.queryTotal(params);

        Page<DeviceDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<DeviceDto>>ok().wrap(page);
    }

    /**
     * 组下边的设备
     */
    @GetMapping("deviceList")
    @RequirePermissions(values = "sysGroup:deviceList")
    @Operation(summary = "查询系统组授权的设备列表")
    public Response<Page<DeviceDto>> list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Request request = Request.configParams(params);

        SysGroupDto sysGroupDto = sysGroupService.selectById(request.getLong("groupId"));
        if (sysGroupDto == null) {
            throw new CheckErrorException("用户组ID必须分配");
        }
        super.fillTenantData(params);
        params.put("_sysGroup", sysGroupDto);

        List<DeviceDto> list = deviceService.queryList(params);
        int total = deviceService.queryTotal(params);

        Page<DeviceDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<DeviceDto>>ok().wrap(page);
    }

    /**
     * 系统组管理设备导出
     */
    @GetMapping("deviceExport")
    @RequirePermissions(values = "sysGroup:deviceExport")
    @Operation(summary = "系统组管理设备导出")
    public void list(@RequestParam Map<String, Object> params, HttpServletResponse httpServletResponse) {

        //查询列表数据
        Request request = Request.configParams(params);

        SysGroupDto sysGroupDto = sysGroupService.selectById(request.getLong("groupId"));
        if (sysGroupDto == null) {
            throw new CheckErrorException("用户组ID必须分配");
        }
        params.put("_sysGroup", sysGroupDto);

        //查询列表数据 防止数据过大分页查询
        List<DeviceDto> allList = new ArrayList<>();
        int pageNo = 0;
        while (true) {
            params.put("limit", 1000);
            params.put("offset", (++pageNo - 1) * 1000);
            List<DeviceDto> list = deviceService.queryList(params);
            if (list != null && list.size() <= 0) {
                break;
            }
            allList.addAll(list);

        }
        String[] headers = new String[]{"设别码", "名称", "IMEI", "经度", "经度"};

        List<String[]> dataList = new ArrayList<>();
        for (DeviceDto deviceDto : allList) {
            String[] item = new String[headers.length];
            item[0] = deviceDto.getUniqueId();
            item[1] = deviceDto.getName();
            item[2] = deviceDto.getImei();
            item[3] = deviceDto.getLongitude() != null ? deviceDto.getLongitude().toString() : "";
            item[4] = deviceDto.getLatitude() != null ? deviceDto.getLongitude().toString() : "";
            dataList.add(item);
        }

        POIUtils.exportExcel(httpServletResponse, "设备列表", headers, dataList, "设备列表");
    }

    @PostMapping(value = "importDevice")
    @RequirePermissions(values = "sysGroup:authorize")
    @Operation(summary = "系统组设备信息导入")
    public Response<Object> uploadIcon(MultipartHttpServletRequest request) {
        String groupId = httpServletRequest.getParameter("groupId");
        String parentGroupId = httpServletRequest.getParameter("parentGroupId");

        //查询父级组所管理的设备 防止用户多导入
        List<DeviceDto> parentGroupMangeDeviceList = new ArrayList<>();
        SysGroupDto sysGroupDto = sysGroupService.selectById(Long.valueOf(parentGroupId));
        HashMap<String, Object> params = new HashMap<>();
        params.put("_sysGroup", sysGroupDto);
        params.put("limit", 1000);
        int pageNo = 1;
        while (true) {
            params.put("offset", (pageNo - 1) * 1000);
            List<DeviceDto> deviceDtoList = deviceService.queryList(params);
            if (deviceDtoList.size() <= 0) {
                break;
            }
            parentGroupMangeDeviceList.addAll(deviceDtoList);
            pageNo++;
        }

        /*        sysGroupDeviceService.deleteByGroupId(Long.valueOf(groupId));
         */
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                try {
                    InputStream inputStream = file.getInputStream();
                    List<Map<Integer, String>> analysis = POIUtils.analysis(inputStream, 1, 0);
                    int i = 0;
                    if (analysis != null && analysis.size() >= 0) {
                        for (Map map : analysis) {
                            String imei = (String) map.get(0);

                            DeviceDto deviceDto = deviceService.selectCacheByImei(imei, SessionHolder.getSysUser().getTenantId());
                            if (deviceDto != null) {
                                for (DeviceDto dto : parentGroupMangeDeviceList) {
                                    if (dto.getId().equals(deviceDto.getId())) {
                                        SysGroupDeviceDto sysGroupDeviceDto = new SysGroupDeviceDto();
                                        sysGroupDeviceDto.setDeviceId(deviceDto.getId());
                                        sysGroupDeviceDto.setSysGroupId(Long.valueOf(groupId));

                                        //先删除用户组跟设备ID的关系
                                        sysGroupDeviceService.deleteByGroupIdAndDeviceId(Long.valueOf(groupId), deviceDto.getId());
                                        sysGroupDeviceService.save(sysGroupDeviceDto);
                                        i++;
                                    }
                                }

                            }
                        }
                    }
                    return Response.ok().wrap("已经成功导入" + i + "台设备,如果发现导入数量小于Excel的数量检查该设备是否存在或者父级是否拥有管理该设备的权限");
                } catch (Exception e) {
                    return Response.error("上传失败,请检查文件类型");
                }
            }
        }
        return Response.error("上传失败");
    }

    /**
     * 系统组类型权限保存
     */
    @PostMapping("saveGroupAuthority")
    @RequirePermissions(values = "sysGroup:authorize")
    @Operation(summary = "系统组类型权限保存")
    public Response<Object> saveGroupAuthority(@RequestBody SysGroupAuthrityInfoVo sysGroupAuthrityInfoVo) {
        //先清除组的设备种类和设备类型
        sysGroupDeviceCategoryService.deleteByGroupId(sysGroupAuthrityInfoVo.getGroupId());
        sysGroupDeviceTypeService.deleteByGroupId(sysGroupAuthrityInfoVo.getGroupId());

        //查询我可以分配的设备种类进行校验  防止用户注入
        Response<Map<String, Object>> groupDeviceCategory = queryGroupDeviceCategory(sysGroupAuthrityInfoVo.getParentGroupId(), sysGroupAuthrityInfoVo.getGroupId());
        List<Map<String, Object>> deviceCategoryDtoList = (List<Map<String, Object>>) groupDeviceCategory.getData().get("canSelectDeviceCategories");
        if (deviceCategoryDtoList != null && deviceCategoryDtoList.size() > 0) {
            for (Map<String, Object> deviceCategoryDto : deviceCategoryDtoList) {
                List<Long> recDeviceCategoryIds = sysGroupAuthrityInfoVo.getGroupDeviceCategoryIds();
                if (recDeviceCategoryIds != null && recDeviceCategoryIds.size() > 0) {
                    for (Long recCategoryId : recDeviceCategoryIds) {
                        if (recCategoryId.equals(deviceCategoryDto.get("key"))) {
                            //前端传入的id符合父级组管理的最大管理权
                            SysGroupDeviceCategoryDto sysGroupDeviceCategoryDto = new SysGroupDeviceCategoryDto();
                            sysGroupDeviceCategoryDto.setSysGroupId(sysGroupAuthrityInfoVo.getGroupId());
                            sysGroupDeviceCategoryDto.setDeviceCategoryId(recCategoryId);
                            sysGroupDeviceCategoryService.save(sysGroupDeviceCategoryDto);
                        }
                    }
                }
            }
        }
        //查询我可以分配的设备类型进行校验  防止用户注入
        Response<Map<String, Object>> groupDeviceType = queryGroupDeviceType(sysGroupAuthrityInfoVo.getParentGroupId(), sysGroupAuthrityInfoVo.getGroupId());
        List<Map<String, Object>> deviceTypeDtoList = (List<Map<String, Object>>) groupDeviceType.getData().get("canSelectDeviceTypes");
        if (deviceTypeDtoList != null && deviceTypeDtoList.size() > 0) {
            for (Map<String, Object> deviceTypeDto : deviceTypeDtoList) {
                List<Long> recDeviceTypeIds = sysGroupAuthrityInfoVo.getGroupDeviceTypeIds();
                if (recDeviceTypeIds != null && recDeviceTypeIds.size() > 0) {
                    for (Long recDeviceId : recDeviceTypeIds) {
                        if (recDeviceId.equals(deviceTypeDto.get("key"))) {
                            //前端传入的id符合父级组管理的最大管理权
                            SysGroupDeviceTypeDto sysGroupDeviceTypeDto = new SysGroupDeviceTypeDto();
                            sysGroupDeviceTypeDto.setSysGroupId(sysGroupAuthrityInfoVo.getGroupId());
                            sysGroupDeviceTypeDto.setDeviceTypeId(recDeviceId);
                            sysGroupDeviceTypeService.save(sysGroupDeviceTypeDto);
                        }
                    }
                }
            }
        }

        return Response.ok();
    }


    /**
     * 查询现在改组可以选择的设备和目前该组拥有的设备种类
     */
    @GetMapping("queryGroupDeviceCategory")
    @RequirePermissions(values = "sysGroup:authorize")
    @Operation(summary = "查询现在改组可以选择的设备和目前该组拥有的设备种类")
    public Response<Map<String, Object>> queryGroupDeviceCategory(@RequestParam Long parentGroupId, @RequestParam Long groupId) {
        Map<String, Object> result = new HashMap<>();

        //查询父级设备种类范围
        //默认值
        List<DeviceCategoryDto> parentCategoryDtoList = new ArrayList<>();

        SysGroupDto sysGroupDto = sysGroupService.selectById(parentGroupId);
        if (sysGroupDto != null) {

            if (SysConstants.SYS_TOP_GROUP_CODE.equalsIgnoreCase(sysGroupDto.getCode())) {
                //超级组查询所有设备种类
                parentCategoryDtoList = deviceCategoryService.queryList(new HashMap<>());
            } else {
                parentCategoryDtoList = sysGroupDeviceCategoryService.selectByGroupId(parentGroupId);
            }

        }

        result.put("canSelectDeviceCategories", parentCategoryDtoList.stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("key", o.getId());
            map.put("label", o.getName());
            return map;
        }).collect(Collectors.toList()));


        //目前自己管理的id
        List<DeviceCategoryDto> deviceCategoryDtoList = sysGroupDeviceCategoryService.selectByGroupId(groupId);
        result.put("groupDeviceCategoryIds", deviceCategoryDtoList.stream().map(DeviceCategoryDto::getId).collect(Collectors.toList()));

        return Response.<Map<String, Object>>ok().wrap(result);
    }

    /**
     * 查询现在改组可以选择的设备和目前该组拥有的设备类型
     */
    @GetMapping("queryGroupDeviceType")
    @RequirePermissions(values = "sysGroup:authorize")
    @Operation(summary = "查询现在改组可以选择的设备和目前该组拥有的设备类型")
    public Response<Map<String, Object>> queryGroupDeviceType(@RequestParam Long parentGroupId, @RequestParam Long groupId) {
        Map<String, Object> result = new HashMap<>();

        //查询父级设备种类范围
        //默认值
        List<DeviceTypeDto> parentTypeDtoList = new ArrayList<>();

        SysGroupDto sysGroupDto = sysGroupService.selectById(parentGroupId);
        if (sysGroupDto != null) {
            if (SysConstants.SYS_TOP_GROUP_CODE.equalsIgnoreCase(sysGroupDto.getCode())) {
                //超级组查询所有设备种类
                parentTypeDtoList = deviceTypeService.queryList(new HashMap<>());
            } else {
                parentTypeDtoList = sysGroupDeviceTypeService.selectByGroupId(parentGroupId);
            }
        }

        result.put("canSelectDeviceTypes", parentTypeDtoList.stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("key", o.getId());
            map.put("label", o.getName());
            return map;
        }).collect(Collectors.toList()));

        //目前自己管理的id
        List<DeviceTypeDto> deviceTypeDtoList = sysGroupDeviceTypeService.selectByGroupId(groupId);
        result.put("groupDeviceTypeIds", deviceTypeDtoList.stream().map(DeviceTypeDto::getId).collect(Collectors.toList()));

        return Response.<Map<String, Object>>ok().wrap(result);
    }

    /**
     * 系统组列表查询
     */
    @GetMapping("list")
    @RequirePermissions(values = "sysGroup:list")
    @Operation(summary = "系统组列表查询")
    public Response<List<SysGroupDto>> list() {
        //查询列表数据
        Long groupId = SessionHolder.getSysUser().getGroupId();
        if (groupId == null || groupId < 0) {
            return Response.<List<SysGroupDto>>ok().wrap(new ArrayList<>());
        }
        List<SysGroupDto> sysGroupDtoList = sysGroupService.selectByParentId(groupId);
        sysGroupDtoList.add(sysGroupService.selectById(groupId));
        return Response.<List<SysGroupDto>>ok().wrap(sysGroupDtoList);
    }


    /**
     * 根据ID查询系统组记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "sysGroup:info")
    @Operation(summary = "根据ID查询系统组记录")
    public Response<SysGroupDto> info(@PathVariable("id") Long id) {

        SysGroupDto sysGroupDto = sysGroupService.selectById(id);
        if (Objects.nonNull(sysGroupDto)) {
            if (SysGroupConstants.IsPartyManagerEnum.IS_MANAGER.getIsPartyManager().equals(sysGroupDto.getIsPartyManager())) {
                // 党组织管理
                PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectById(sysGroupDto.getPartyId());
                if (Objects.isNull(partyOrganizationDto)) {
                    sysGroupDto.setPartyId(null);
                }
            }

            if (SysConstants.GroupAuthEnum.BY_REGION.getType().equals(sysGroupDto.getAuthorityType())) {
                SysGroupRegionDto sysGroupRegionDto = sysGroupRegionService.queryOneByGroupId(sysGroupDto.getId());
                if (Objects.nonNull(sysGroupRegionDto)) {
                    sysGroupDto.setRegionCode(Objects.requireNonNull(RegionUtils.getByCode(sysGroupRegionDto.getCode())).getCode());
                    sysGroupDto.setRegionName(Objects.requireNonNull(RegionUtils.getByCode(sysGroupRegionDto.getCode())).getName());
                }
            }
        }

        return Response.<SysGroupDto>ok().wrap(sysGroupDto);
    }

    /**
     * 保存系统组记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "sysGroup:edit")
    @Operation(summary = "保存系统组记录")
    public Response<Object> save(@RequestBody @Validated SysGroupDto sysGroupDto) {

        LoginUserSession loginUser = SessionHolder.getSysUser();
        SysGroupDto dbValue = sysGroupService.selectByCode(sysGroupDto.getCode(), loginUser.getTenantId());
        if (!Objects.isNull(dbValue)) {
            return Response.error("组编码已存在");
        }

        fillSaveCommonData(sysGroupDto);

        if (SysConstants.GroupAuthEnum.BY_REGION.getType().equals(sysGroupDto.getAuthorityType())) {
            boolean b = regionGroupHandle(sysGroupDto, RegionOpeEnum.ADD);
            if (!b) {
                return Response.error("区域组创建异常");
            }
        } else {
            sysGroupService.save(sysGroupDto);
        }
        return Response.ok();
    }

    private enum RegionOpeEnum {
        // 区域组操作类型
        ADD, UPDATE
    }

    /**
     * 区域组操作方法
     * 未在事务下进行 所有操作均获取租户锁
     *
     * @param sysGroupDto 操作的区域用户组
     * @param opeEnum     操作类型
     * @return
     */
    private boolean regionGroupHandle(SysGroupDto sysGroupDto, RegionOpeEnum opeEnum) {


        if (!SysConstants.GroupAuthEnum.BY_REGION.getType().equals(sysGroupDto.getAuthorityType())) {
            logger.warn("用户组操作，非区域组");
            return Boolean.FALSE;
        }

        SysGroupDto sysParentGroupDto = sysGroupService.selectById(sysGroupDto.getParentId());

        if (Objects.isNull(sysParentGroupDto)) {
            logger.warn("用户组区域授权 父级组不存在");
            return Boolean.FALSE;
        }
        if (!SysConstants.SYS_TOP_GROUP_CODE.equals(sysParentGroupDto.getCode())
                && !SysConstants.GroupAuthEnum.BY_REGION.getType().equals(sysParentGroupDto.getAuthorityType())) {
            logger.warn("用户组区域授权 错误的父子组权限关系");
            return Boolean.FALSE;
        }

        LoginUserSession sysUser = SessionHolder.getSysUser();
        Preconditions.checkNotNull(sysUser);

        Lock spinLock = RedisUtils.getSpinLock(REGION_GROUP_OPERATE_LOCK + sysUser.getTenantId());
        spinLock.lock();
        try {
            switch (opeEnum) {
                case ADD:
                    SysGroupRegionDto oldRegionRefAdd = sysGroupRegionService.queryOneByTenantAndRQ(sysUser.getTenantId(), sysGroupDto.getRegionCode());
                    if (Objects.nonNull(oldRegionRefAdd)) {
                        logger.warn("用户组区域授权 该区域已授权给 groupId {}", oldRegionRefAdd.getSysGroupId());
                        throw new RuntimeException("This area is authorized.");
                    }
                    Long save = sysGroupService.save(sysGroupDto);

                    SysGroupRegionDto sysGroupRegionDto = sysGroupRegionService.queryOneByGroupId(sysGroupDto.getParentId());
                    //如果是顶级
                    if (Objects.nonNull(save) && sysGroupRegionDto == null) {
                        SysGroupRegionDto newlyDto = new SysGroupRegionDto();
                        newlyDto.setSysGroupId(save);
                        newlyDto.setCode(sysGroupDto.getRegionCode());
                        newlyDto.setTenantId(sysUser.getTenantId());
                        newlyDto.setType(sysGroupDto.getRegionLevel().intValue());
                        sysGroupRegionService.save(newlyDto);
                    }

                    if (Objects.nonNull(save) && sysGroupRegionDto != null
                            && (SysConstants.SYS_TOP_GROUP_CODE.equals(sysParentGroupDto.getCode())
                            || sysGroupDto.getRegionCode().startsWith(sysGroupRegionDto.getCode()))) {
                        SysGroupRegionDto newlyDto = new SysGroupRegionDto();
                        newlyDto.setSysGroupId(save);
                        newlyDto.setCode(sysGroupDto.getRegionCode());
                        newlyDto.setTenantId(sysUser.getTenantId());
                        newlyDto.setType(sysGroupDto.getRegionLevel().intValue());
                        sysGroupRegionService.save(newlyDto);
                    }
                    break;
                case UPDATE:
                    SysGroupRegionDto dbGroupRegion = sysGroupRegionService.queryOneByGroupId(sysGroupDto.getId());
                    Preconditions.checkNotNull(dbGroupRegion);

                    if (!dbGroupRegion.getCode().equals(sysGroupDto.getRegionCode())) {
                        SysGroupRegionDto oldRegionRefUpdate = sysGroupRegionService.queryOneByTenantAndRQ(sysUser.getTenantId(), sysGroupDto.getRegionCode());
                        if (Objects.nonNull(oldRegionRefUpdate)) {
                            logger.warn("用户组区域授权 该区域已授权给 groupId {}", oldRegionRefUpdate.getSysGroupId());
                            throw new RuntimeException("This area is authorized.");
                        }

                        RegionUtils.ReignStruct byCode = RegionUtils.getByCode(sysGroupDto.getRegionCode());
                        Preconditions.checkNotNull(byCode);

                        SysGroupRegionDto newlyDto = new SysGroupRegionDto();
                        newlyDto.setId(dbGroupRegion.getId());
                        newlyDto.setType(byCode.getLevel().intValue());
                        newlyDto.setCode(byCode.getCode());
                        sysGroupRegionService.updateById(newlyDto);
                    }
                    sysGroupService.updateById(sysGroupDto);
                    break;
                default:
                    logger.warn("用户组区域授权 错误的操作类型");
                    break;
            }
            return Boolean.TRUE;
        } catch (Exception e) {
            logger.error("区域组权限操作异常", e);
        } finally {
            spinLock.unlock();
        }
        return Boolean.FALSE;
    }

    /**
     * 修改系统组记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "sysGroup:edit")
    @Operation(summary = "修改系统组记录")
    public Response<Object> update(@RequestBody @Validated SysGroupDto sysGroupDto) {

        LoginUserSession loginUser = SessionHolder.getSysUser();
        SysGroupDto dbValueByCode = sysGroupService.selectByCode(sysGroupDto.getCode(), loginUser.getTenantId());

        if (SysConstants.SYS_TOP_GROUP_CODE.equals(dbValueByCode.getCode())) {
            return Response.error("系统组不允许修改");
        }
        if (!Objects.isNull(dbValueByCode) && !Objects.equals(sysGroupDto.getId(), dbValueByCode.getId())) {
            return Response.error("组编码已存在");
        }
        SysGroupDto dbValueById = sysGroupService.selectById(sysGroupDto.getId());
        if (dbValueById != null) {
            if (!Objects.equals(dbValueById.getAuthorityType(), sysGroupDto.getAuthorityType())) {
                //编辑组如果更换授权类型需要删除上一次已经关联的授权记录
                clearAuthByGroupId(dbValueById.getId());
            }
        }

        //填充基础数据
        fillEditCommonData(sysGroupDto);
        if (SysConstants.GroupAuthEnum.BY_REGION.getType().equals(sysGroupDto.getAuthorityType())) {
            boolean b = regionGroupHandle(sysGroupDto, RegionOpeEnum.UPDATE);
            if (!b) {
                return Response.error("区域组编辑异常");
            }
        } else {
            sysGroupService.updateById(sysGroupDto);
        }

        return Response.ok();
    }

    /**
     * 删除系统组记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "sysGroup:delete")
    @Operation(summary = "删除系统组记录")
    public Response<Object> delete(@RequestBody Long[] ids) {
        for (Long id : ids) {
            List<SysUserDto> subUsers = sysGroupService.getSubUsers(id);
            if (subUsers != null && subUsers.size() > 0) {
                return Response.error("组织机构存在用户，不允许删除");
            }
        }
        for (Long id : ids) {
            clearAuthByGroupId(id);
            sysGroupService.deleteById(id);
        }
        return Response.ok();
    }

    private void clearAuthByGroupId(Long groupId) {
        SysGroupDto sysGroupDto = sysGroupService.selectById(groupId);
        if (sysGroupDto == null) {
            return;
        }
        if (SysConstants.GroupAuthEnum.BY_REGION.getType().equals(sysGroupDto.getAuthorityType())) {
            sysRegionVillageRefService.deleteByGroupId(groupId);
            sysGroupRegionService.deleteByGroupId(groupId);
        } else if (SysConstants.GroupAuthEnum.BY_VILLAGE.getType().equals(sysGroupDto.getAuthorityType())) {
            sysGroupVillageService.deleteByGroupId(groupId);
        } else if (SysConstants.GroupAuthEnum.BY_BUILDING.getType().equals(sysGroupDto.getAuthorityType())) {
            sysGroupBuildingService.deleteByGroupId(groupId);
        } else if (SysConstants.GroupAuthEnum.BY_TYPE.getType().equals(sysGroupDto.getAuthorityType())) {
            sysGroupDeviceCategoryService.deleteByGroupId(groupId);
            sysGroupDeviceTypeService.deleteByGroupId(groupId);
        } else if (SysConstants.GroupAuthEnum.BY_DEVICE.getType().equals(sysGroupDto.getAuthorityType())) {
            sysGroupDeviceService.deleteByGroupId(groupId);
        }
    }


}
